using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;

[ExecuteInEditMode]
public class PathPairBehaviour : SolidColorGizmo 
{
	public PathPair pathPair
	{
		set 
		{
			m_pathPair = value;
		}
		get 
		{
			return m_pathPair;
		}
	}
	
	public int sampleTimes
	{
		set 
		{
			m_sampleTimes = value;
			if (m_pathPair != null)
			{
				m_pathPair.Sample (m_sampleTimes);
			}
		}
		get 
		{
			return m_sampleTimes; 
		}
	}
	
	public PathMap pathMap 
	{
		set 
		{
			m_pathMap = value;
		}
	}
	
	public bool curveCreated 
	{
		get { return m_curveCreated; }
	}
	
	public Vector3 startAnchor
	{
		set
		{
			if (m_startAnchorSet) return;
			
			m_startAnchorSet = true;
			m_startAnchor = value;
		}
	}
	
	public bool startAnchorSet
	{
		get 
		{
			return m_startAnchorSet;
		}
	}	
	
	public Vector3 endAnchor 
	{
		set
		{
			if (m_endAnchorSet) return;
			
			m_endAnchorSet = true;
			m_endAnchor = value;
			
			PathQuinticBezier rawPath = new PathQuinticBezier (m_startAnchor, m_endAnchor);
			m_pathPair = new PathPair (rawPath);
			m_pathPair.Sample (m_sampleTimes);
			/*
			m_bezier = new PathQuinticBezier (m_startAnchor, m_endAnchor);
			m_bezier.Sample (m_sampleTimes);
			*/
			m_anchorObjects = new List<GameObject> ();
			for (int i = 0, len = m_pathPair.anchorCount; i < len; ++ i)
			{
				GameObject anchorHost = new GameObject ("P" + i);
				anchorHost.transform.parent = gameObject.transform;
				anchorHost.transform.position = m_pathPair.GetAnchor (i);
				m_anchorObjects.Add (anchorHost);
			}
			
			m_curveCreated = true;
			
			if (m_pathMap !=  null)
			{
				m_pathMap.AddPath (m_pathPair);
			}
		}
	}
	
	public bool endAnchorSet
	{
		get
		{
			return m_endAnchorSet;
		}
	}
	
	protected override void DrawGizmos ()
	{
		if (curveCreated)
		{
			m_pathPair.Render ();
		}
	}
	
	void Update ()
	{
		if (m_pathPair != null)
		{
			if (Selection.activeGameObject.transform.parent != gameObject.transform)
			{
				return;
			}
			
			bool anchorPosChanged = false;
			for (int i = 0, len = m_pathPair.anchorCount; i < len; ++ i)
			{
				Vector3 anchorPos = m_anchorObjects[i].transform.position;
				bool currentAnchorChanged = !(m_pathPair.GetAnchor (i).Equals (anchorPos));
				
				if (currentAnchorChanged)
				{
					m_pathPair.SetAnchor (i, anchorPos);
				}
				
				anchorPosChanged |= currentAnchorChanged;
			}
			
			if (anchorPosChanged)
			{
				m_pathPair.Sample (m_sampleTimes);
			}
		}
	}
	
	PathPair m_pathPair = null;
	
	bool m_curveCreated = false;
	
	Vector3 m_startAnchor = Vector3.zero;
	
	bool m_startAnchorSet = false;
	
	Vector3 m_endAnchor = Vector3.zero;
	
	bool m_endAnchorSet = false;
	
	List<GameObject> m_anchorObjects;
	
	public int m_sampleTimes = 500;
	
	private PathMap m_pathMap = null;
}
